package com.dlc.beijingrfid.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import butterknife.BindView;
import butterknife.OnClick;
import com.dlc.beijingrfid.R;
import com.dlc.beijingrfid.adapter.CheckDetailsAdapter;
import com.dlc.beijingrfid.base.BaseActivity;
import com.dlc.beijingrfid.helper.DBManager;
import com.dlc.beijingrfid.net.bean.RFIDBean;
import com.dlc.beijingrfid.net.bean.RFIDListBean;
import com.dlc.beijingrfid.net.bean.SaveRfidBean;
import com.dlc.beijingrfid.net.bean.StockCheckBean;
import com.dlc.beijingrfid.net.bean.StockCheckData;
import com.dlc.beijingrfid.net.protocol.CountingProto;
import com.dlc.beijingrfid.net.protocol.StockProto;
import com.dlc.commonlibrary.ble.BleWorker;
import com.dlc.commonlibrary.ble.RfidHelper;
import com.dlc.commonlibrary.dialog.DoResultDialog;
import com.dlc.commonlibrary.dialog.SureDialog;
import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.commonlibrary.utils.RecyclerViewUtil;
import com.dlc.commonlibrary.utils.ToastUtil;
import com.dlc.commonlibrary.widget.CommonItemView;
import com.dlc.commonlibrary.widget.TitleBar;
import com.lzy.okgo.model.HttpParams;
import java.util.ArrayList;
import java.util.List;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * todo 盘点详情页，列表还没做好
 */
public class CountingDetailActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    TitleBar mTitleBar;
    @BindView(R.id.item_kucun_record_amount)
    CommonItemView mItemKucunRecordAmount;
    @BindView(R.id.item_counting_amount)
    CommonItemView mItemCountingAmount;
    @BindView(R.id.item_difference_amount)
    CommonItemView mItemDifferenceAmount;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.btn_read_rfid)
    Button mBtnReadRfid;
    @BindView(R.id.btn_commit_counting)
    Button mBtnCommitCounting;
    @BindView(R.id.item_real_counting_amount)
    CommonItemView itemRealCountingAmount;//扫描到的所有RFID

    private CheckDetailsAdapter mCheckDetailsAdapter;

    // TODO: 2017/7/19 临时handler 

    private String warehouseId;
    private String wareFrameId;
    private String stockno;
   // private ProductAbnormalAdapter adapter;
    private DoResultDialog doResultDialog, doReadDialog;

    private StringBuilder mStringBuilder;
    private ArrayList<String> RfList = new ArrayList<>();//扫描到的所有RFID
    private List<StockCheckData> mStockCheckList = new ArrayList<>();
    private int exisNumber = 0;//存在仓库的数据
    private int differenceData = 0;
    private DBManager dbManager = DBManager.getInstance(this);
    private ArrayList<String> saveList = new ArrayList<>();//在数据库中保存的RFID
    List<String> SumList = new ArrayList<>();
    BleWorker mBleWorker = new BleWorker();
    private int counts = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mTitleBar.leftExit(this);

        // TODO: 2017/7/19 临时代码 ------start

        counts = getIntent().getIntExtra("counts",0);
        warehouseId = getIntent().getStringExtra("warehouseId");
        wareFrameId = getIntent().getStringExtra("wareFrameId");

        mCheckDetailsAdapter = new CheckDetailsAdapter();

        mItemKucunRecordAmount.setContent(String.valueOf(counts));
        doReadRFID();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mCheckDetailsAdapter.addHeaderView( LayoutInflater.from(CountingDetailActivity.this).inflate(R.layout.item_check_details, null, false));
        mRecyclerView.setLayoutManager(linearLayoutManager);
        RecyclerViewUtil.setDefaultDivider(mRecyclerView, linearLayoutManager);
        mRecyclerView.setAdapter(mCheckDetailsAdapter);
        itemRealCountingAmount.setContent(String.valueOf(RfList.size()));
        getDbData();
        mBleWorker.setCallback(new BleWorker.ReadCallback() {
            @Override
            public void onReceiveData(ArrayList<String> rfList,int readNum) {
                RfList = rfList;

                LogPlus.e(RfList.toString());
                itemRealCountingAmount.setContent(String.valueOf(RfList.size()));
                doReadDialog.showResultAndDismiss(true, 1000);
                if (RfList != null && RfList.size() > 0) {
                    savaDb(RfList);
                    getDataDetails(RfList);
                }
            }

            @Override
            public void onDeviceDisconnected() {
                doReadDialog.dismiss();
                Intent intent = new Intent(CountingDetailActivity.this,MainActivity.class);
                intent.putExtra("type","2");
                startActivity(intent);
                finish();
            }
            @Override
            public void onErrorNumber(int number) {
                if (number > 0) {
                    showOneToast("存在长度小于14的标签" + number + "个");
                }
            }
        });
        // TODO: 2017/7/19 临时代码 ------end
    }

    /**
     * 获取数据库的数据
     */
    private void getDbData(){
        List<SaveRfidBean> list = dbManager.queryLabelList();
        for (SaveRfidBean bean:list){
            saveList.add(bean.getRfid());
        }
        if (saveList.size() > 0){
            getDataDetails(null);
        }
    }





    @Override
    protected int getLayoutID() {
        return R.layout.activity_counting_detail;
    }

    @OnClick({R.id.btn_read_rfid, R.id.btn_commit_counting})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_read_rfid:
                getData();
                //RfList.add("00393B7B34CE");
                //RfList.add("00393B7B4076");
                //RfList.add("00393B7B3411");
                //getDataDetails(RfList);
                break;
            case R.id.btn_commit_counting:
                SureDialog sureDialog = new SureDialog(CountingDetailActivity.this,"全部读取完成，确认提交");
                sureDialog.setOnCallBackListener(new SureDialog.OnCallBack() {
                    @Override
                    public void sure() {
                        doCommitResult();
                    }

                    @Override
                    public void cancle() {

                    }
                });

                break;
        }
    }

    private void doReadRFID() {
        doReadDialog =
                DoResultDialog.newDialog(this).
                        setWorkingText(getString(R.string.read_rfid_ing))
                        .setSuccessImage(R.mipmap.ic_success)
                        .setSuccessText(getString(R.string.scan_over))
                        .setButton("完成扫描", new DoResultDialog.OnClickButtonListener() {
                            @Override
                            public void onClickButton(DoResultDialog dialog) {
                                mBleWorker.cancelCheck();
                            }
                        });

        doReadDialog.setCancelable(false);

    }

    private void getData(){
        if ( counts == 0) {
            showToast("未获得订单数据");
            return;
        }
        doReadDialog.showWorking(true);
        mBleWorker.check();
    }





    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case 1:
//                    doReadDialog.showResultAndDismiss(true, 1000);
//                    endReadRFID();
//                    break;
//            }
        }
    };

    //private void judgeData() {
    //    runOnUiThread(new Runnable() {
    //        @Override
    //        public void run() {
    //            if (!isBleStop) {
    //                RfList.clear();
    //                if (rfidsList.size() > 0) {
    //                    if (rfidsList.size() == cashCount || TYPE == 2) {//获取到的缓存区数量相等或者是直接获取缓存数据
    //                        doReadDialog.dismiss();
    //                        for (String str : rfidsList) {
    //                            if (str.length() > 14) {
    //                                str = str.substring(str.length() - 12, str.length());
    //                                RfList.add(str);
    //                            }
    //                        }
    //                        itemRealCountingAmount.setContent(String.valueOf(RfList.size()));
    //                        savaDb(RfList);
    //                        getDataDetails(RfList);
    //                    } else {
    //                        //ToastUtil.show(getContext(),"获取的数量不对应，直接获取读到的缓存rfid");
    //                        TYPE = 2;
    //                        rfidsList.clear();
    //                        RRUA100API.getInstance(new Handler()).A100_getSyncTagList();
    //                    }
    //                }
    //            }else {
    //                doReadDialog.dismiss();
    //                showToast("未连接设备，跳到连接页面");
    //                Intent intent = new Intent(getActivity(),MainActivity.class);
    //                intent.putExtra("type", "2");
    //                startActivity(intent);
    //            }
    //        }
    //    });
    //
    //}

    /**
     * 保存数据到数据库
     */
    private void savaDb(ArrayList<String> list){
        for (String string:list){
            SaveRfidBean bean = new SaveRfidBean(null,string);
            dbManager.insertLabel(bean);
        }
    }




    private void doCommitResult() {
        if (SumList.size() == 0) {
            ToastUtil.show(CountingDetailActivity.this,"没有要提交的数据");
            return;
        }
        doResultDialog = DoResultDialog.newDialog(this)
                .setWorkingText(getString(R.string.commit_counting_result))
                .setSuccessImage(R.mipmap.ic_success)
                .setSuccessText(getString(R.string.commit_counting_result_success));

        doResultDialog.setCancelable(false);
        doResultDialog.showWorking();
        submitData();
    }

    /**
     * 盘点提交
     */
    private void submitData() {
        StringBuilder sb = new StringBuilder();
        //for(String rfid : SumList){
        //    sb.append(rfid+",");
        //}
        //String data = sb.substring(0,sb.length()-1);
        HttpParams params = new HttpParams();
        params.put("stockno", stockno);
        params.put("warehouse_id", warehouseId);
       // params.put("ware_frame_id", wareFrameId);
        params.put("warecount", mItemKucunRecordAmount.getContentText());
        params.put("stockcount", itemRealCountingAmount.getContentText());
       // params.put("rfids", data);

        String rfid = "";

        for (int i = 0; i < SumList.size(); i++) {
            rfid = rfid + SumList.get(i) + ",";
        }

        if (!TextUtils.isEmpty(rfid))
            rfid = rfid.substring(0, rfid.length() - 1);
        params.put("rfids", rfid);
        CountingProto.get().stock(params).
                subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Observer<Object>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        LogPlus.e(e.getMessage());
                        doResultDialog.setFailedText(e.getMessage());
                        doResultDialog.setFailedImage(R.mipmap.ic_error);
                        doResultDialog.showResultAndDismiss(false, 2000);
                    }

                    @Override
                    public void onNext(Object data) {
                        dbManager.deleteLabelAll();
                        SumList.clear();
                        mStockCheckList.clear();
                        mCheckDetailsAdapter.notifyDataSetChanged();
                        itemRealCountingAmount.setContent("0");
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (doResultDialog != null) {
                                    doResultDialog.showResultAndDismiss(true, 1000);
                                }

                            }
                        });
                    }
                });
    }

    /**
     * 获取标签数据
     */
    @NonNull
    private void initFakeData(final List<String> dflist,final List<RFIDBean.DataBean.ListBean> list) {
        StringBuilder sb = new StringBuilder();
        for(String rfid : dflist){
            sb.append(rfid+",");
        }
        String data = sb.substring(0,sb.length()-1);
        StockProto.get()
                .query_by_rfid(data,"1","100")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RFIDListBean.DataBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtil.show(getActivity(), e.getMessage());
                        addfind(dflist,list);
                    }

                    @Override
                    public void onNext(RFIDListBean.DataBean bean) {
                        ArrayList<String> recordList2 = new ArrayList<>();
                        for (int i = 0;i < bean.list.size();i++){
                            for (int j = 0; j < dflist.size(); j++) {
                                if (bean.list.get(i).cardno.equals(dflist.get(j))) {
                                    recordList2.add(dflist.get(j));
                                    RFIDBean.DataBean.ListBean bean1 = new RFIDBean.DataBean.ListBean();
                                    bean1.setCardno(bean.list.get(i).cardno) ;
                                    bean1.setTitle(bean.list.get(i).title);
                                    bean1.setSpec(bean.list.get(i).spec);
                                    bean1.setWarehouse(bean.list.get(i).warehouse);
                                    bean1 .state = 1;
                                    list.add(bean1);
                                }
                            }
                        }

                        for (int i = 0;i<recordList2.size();i++){
                            dflist.remove(recordList2.get(i));
                        }
                        addfind(dflist,list);
                    }
                });
    }
    private void addfind( List<String> dflist,List<RFIDBean.DataBean.ListBean> list){
        for (int i = 0;i < dflist.size();i++){
            RFIDBean.DataBean.ListBean bean = new RFIDBean.DataBean.ListBean();
            bean.setCardno(dflist.get(i));
            bean .state = 1;
            list.add(bean);
        }
       // adapter.setNewData(list);
    }

    private void getDataDetails(final List<String> dflist){

        if (saveList.size() > 0){
            if (dflist != null) {
                SumList.addAll(dflist);
            }
            SumList.addAll(saveList);
            SumList = RfidHelper.removeDuplicateWithOrder(SumList);
        }else {
            if (dflist != null) {
                SumList.addAll(dflist);
            }
        }
        StringBuilder sb = new StringBuilder();
        for(String rfid : SumList){
            sb.append(rfid+",");
        }
        String data = sb.substring(0,sb.length()-1);
        StockProto.get().stock_check(data,warehouseId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<StockCheckBean.DataBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onNext(StockCheckBean.DataBean dataBean) {
                        doStockData(dataBean);
                        if (dflist == null){
                            SureDialog sureDialog = new SureDialog(CountingDetailActivity.this, "是否清空未提交的數據");
                            sureDialog.setOnCallBackListener(new SureDialog.OnCallBack() {
                                @Override
                                public void sure() {
                                    saveList.clear();
                                    dbManager.deleteLabelAll();
                                    SumList.clear();
                                    mCheckDetailsAdapter.setNewData(null);
                                }

                                @Override
                                public void cancle() {

                                }
                            });
                        }
                    }
                });
    }

    private void doStockData(StockCheckBean.DataBean bean){
        mStockCheckList.clear();
        exisNumber = 0;
        if (bean.list!= null&&bean.list.size()>0) {
            for (int i = 0;i < bean.list.size();i++){
                StockCheckData data = new StockCheckData(bean.list.get(i).goods_name,bean.list.get(i).stock_nums,
                    bean.list.get(i).read_nums,bean.list.get(i).hotel,bean.list.get(i).office);
                exisNumber = exisNumber + Integer.parseInt(bean.list.get(i).read_nums);
                mStockCheckList.add(data);
            }
        }
        if (bean.other!= null&&bean.other.size()>0) {
            for (int i = 0;i < bean.other.size();i++){
                StockCheckData data = new StockCheckData(bean.other.get(i).goods_name+"(其他仓库)","0",
                    bean.other.get(i).nums,bean.list.get(i).hotel,bean.list.get(i).office);
                exisNumber = exisNumber + Integer.parseInt(bean.other.get(i).nums);
                mStockCheckList.add(data);
            }
        }
        int otherNumber = SumList.size() - exisNumber;
        if (otherNumber > 0){
            StockCheckData data = new StockCheckData("品名为空","0",String.valueOf(otherNumber),"","");
            mStockCheckList.add(data);
        }
        mCheckDetailsAdapter.setNewData(mStockCheckList);
    }


}
